const enterpriseVue = new Vue({
  el: '#app',
  data() {
    const Quantity = (rule, value, callback) => {
      if (this.form.Quantity%this.form.Unit_Quantity!=0) {
        callback(new Error('当前上架商品数量不能被最小单元整除'));
      }else if(this.form.Quantity<=this.form.Starting_Quantity){ 
        callback(new Error('当前上架商品数量不能小于起步购买单元量'));
      }else {
        callback();
      }
    }
    const Starting_Quantity = (rule, value, callback) => {
      if (this.form.Starting_Quantity%this.form.Unit_Quantity!=0) {
        callback(new Error('当前起步最低单元量不能被最小单元整除'));
      }else {
        callback();
      }
    }
    return {
      rules: {
        Start_Date: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
        End_Date: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
        Article_SerialNumber: [{ required: true, message: '请选择商品', trigger: 'change' }],
        Quantity: [{ required: true, message: '请输入商品数量', trigger: 'change' },{ required: true, validator:Quantity, trigger: 'change' }],
        Starting_Quantity:[{ required: true, message: '请输入起步最低单元量', trigger: 'change' },{ required: true, validator:Starting_Quantity, trigger: 'change' }]
      },
      Unit_PriceRules: [
        { required: true, message: '请输入价格', trigger: 'blur' },
      ],
      StartNumRules: [
        { required: true, message: '请输入开始数量', trigger: 'blur' },
      ],
      EndNumRules: [
        { required: true, message: '请输入结束数量', trigger: 'blur' },
      ],
      article_info: [],
      article_specifications: [],
      disabled: true,
      disabledSelect: true,
      isDisabled: false,
      form: {     //批发价格单
        Wholesale_Unit_Price_SerialNumber: "",  //主键
        Start_Date: '',
        End_Date: '',
        Submit_Date: "",
        Article_SerialNumber: '',   //商品标识
        Article_Specifications_SerialNumber: '',
        Enterprise_Info_SerialNumber: $.cookie("enterprise"),
        Quantity: 1,
        Starting_Quantity: 1,
        Unit_Quantity: 1,
        Remain_Quantity: 0,
        Sell_Quantity: 0,
        Independence: '0',
        Children: {
          wholesale_unitprice_warehouse: [{
            Wholesale_Unit_Price_Warehouse_SerialNumber: "",
            Wholesale_Unit_Price_SerialNumber: "",
            Warehouse_SerialNumber: "",//仓库流水号
            Warehouse_Sort: 1,//优先级
            Wares: []
          }],
          wholesale_unitprice_paystages: [{
            Wholesale_Unit_Price_Paystages_SerialNumber: "",
            Wholesale_Unit_Price_SerialNumber: "",
            Trading_Explain: "",
            Trading_Detail_SerialNumber: "",
            Trading_Percentage: "",
            Trading_Days: "",
            Min_Quantity: "",
          }]
        }
      },
      PayWay: [{
        Min_Quantity: 0,
        Unit_Price:'',
        checkboxGroup:['0','1'],
        User_Identity:[{
          User_Type:'0',
          Full_Payment: {
            Wholesale_Unit_Price_Paystages_SerialNumber:'',
            Wholesale_Unit_Price_SerialNumber:'',
            Trading_Explain:"全款",
            Trading_Detail_SerialNumber:'T01000000000001',
            Trading_Percentage:95,
            Trading_Days:0,
            Unit_Price:0,
            User_Type:'0',
            Transaction_Type:0,
            Min_Quantity:0,
          },
          Payment_Days: [{
            Wholesale_Unit_Price_Paystages_SerialNumber:'',
            Wholesale_Unit_Price_SerialNumber:'',
            Trading_Explain:'',
            Trading_Detail_SerialNumber:'',
            Trading_Percentage:0,
            Trading_Days:0,
            Unit_Price:0,
            User_Type:'0',
            Transaction_Type:1,
            Min_Quantity:0,
            PaymentDetail:[],
            Sort:''
          },{
            Wholesale_Unit_Price_Paystages_SerialNumber:'',
            Wholesale_Unit_Price_SerialNumber:'',
            Trading_Explain:'',
            Trading_Detail_SerialNumber:'',
            Trading_Percentage:0,
            Trading_Days:0,
            Unit_Price:0,
            User_Type:'0',
            Transaction_Type:1,
            Min_Quantity:0,
            PaymentDetail:[],
            Sort:''
          }],
          isArr:[]
        }]
      }],
      Pay: [],
      Wares: [],
      isWares: [],
      UserType:[{
        id:'0',
        value:'全部'
      }],
      loading: false,
      Enterprise:[]
    }
  },
  mounted() {
    this.getData()
    this.getPaymentDetail()
    this.getUserType()
    // this.PayWay[0].Min_Quantity = this.form.Starting_Quantity
  },
  methods: {
    getData() {
      let _this = this;
      $.ajax({
        url: DomainName + '/getGoodsStatistics?token=' + $.cookie("token"),
        type: 'GET',
        success: function (res) {
          res.forEach(item => {
            item.Remain_Quantity = Number(item.Remain_Quantity)
          })
          _this.article_info = res
        }
      })
    },
    getArticleAll(){
      let _this = this;
      $.ajax({
        url: DomainName + '/getSalesArticleAction?token=' +  $.cookie("token"),
        type: 'POST',
        data: { 
          Enterprise_Info_SerialNumber:$.cookie("enterprise")
        },
        success: function (res) {
          _this.article_info = res.Data
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })
    },
    ChangeNum(e) {
      this.PayWay.forEach((item,i)=>{
        if(i==0){
          this.PayWay[i].Min_Quantity = e
        }else{
          item.Min_Quantity = this.PayWay[0].Min_Quantity*(i+1)
        }
      })
    },
    Independence(e){
      let _this = this
      this.article_info = []
      this.article_specifications = []
      this.form.Article_SerialNumber = ''
      this.form.Article_Specifications_SerialNumber = ''
      if (e==0) {
        this.getData()
        this.disabledSelect = true
      }else{
        this.getArticleAll()
        $.ajax({
          url: DomainName + '/getInquiryAction?token=' + $.cookie("token"),
          type: 'POST',
          data: {
            Data:'warehouse_info',
          },
          success: function (res) {
            console.log(res);
            _this.Wares = res
            _this.form.Children.wholesale_unitprice_warehouse[0].Wares = res
          }
        })
      }
    },
    TypeSort(arr) {
      for (var i = 0; i < arr.length - 1; i++) {
        for (var j = 0; j < arr.length - 1 - i; j++) {
          if (parseInt(arr[j].Sort) > parseInt(arr[j + 1].Sort)) {
            var temp = arr[j];
            arr[j] = arr[j + 1];
            arr[j + 1] = temp;
          }
        }

      }
      return arr
    },
    submitForm(formName) {
      let _this = this
      _this.$refs[formName].validate((valid) => {
        if (valid) {          
          _this.loading = true
          _this.form.Remain_Quantity = _this.form.Quantity
          _this.form.Children.wholesale_unitprice_paystages = []
          let JSONArray = []
          _this.PayWay.forEach(item=>{
            item.User_Identity.forEach(ite=>{
              console.log(item.checkboxGroup);
              let newItem = []
              if(item.checkboxGroup.some(item=>item=='0')){
                JSONArray.push(ite.Full_Payment)
              }
              if(item.checkboxGroup.some(item=>item=='1')){
                newItem = _this.TypeSort(ite.Payment_Days)
              }
              JSONArray = [...JSONArray,...newItem]
            })
          })
          _this.form.Children.wholesale_unitprice_paystages = JSONArray
          _this.form.Submit_Date = getYMDHMSDate()

          
          if(this.form.Independence == '1'){
            //判断外企
            if ($.cookie('enterprise') != this.form.Article_SerialNumber.split('-')[2]) {
              _this.Enterprise.push( this.form.Article_SerialNumber.split('-')[2]);
            }
          }
           //外企企业主键
          let newEnterprise_Info_SerialNumberList = Array.from(new Set(_this.Enterprise))

          $.ajax({
            url: DomainName+'/setUnitPriceAdd?token='+$.cookie("token"),
            type: 'POST',
            data: {
              Data: JSON.stringify({
                wholesale_unitprice: [_this.form]
              }),
              Enterprise_Info_SerialNumber: JSON.stringify(newEnterprise_Info_SerialNumberList)
            },
            success: function (res) {
              if (res.Status === 'success') {
                _this.$message.success("提交成功")
                window.history.go(-1)
              } else {
                _this.$message.error("提交失败，请稍后再试")
              }
            },
            error: function () {
              _this.$message.error("操作失败，请稍后再试")
            },
            complete: function (XMLHttpRequest) {
              _this.loading = false
              if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                window.parent.document.location.href = "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
              }
            }
          })
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    getPaymentDetail() {
      let _this = this;
      $.ajax({
        url: DomainName + '/getInquiryAction?token=' + $.cookie("token"),
        type: 'POST',
        data: {
          Data: 'trading_detail',
          isNullEnterprise: true,
        },
        success: function (res) {
          _this.PayWay[0].User_Identity[0].Payment_Days.forEach(item => {
            item.PaymentDetail = res
          })
          _this.Pay = res
          console.log(_this.PayWay[0].User_Identity[0].Payment_Days);
        }
      })
    },
    Addwholesalepaystages() {
      this.form.Children.wholesale_unitprice_paystages.push({
        Wholesale_Unit_Price_Paystages_SerialNumber: "",
        Wholesale_Unit_Price_SerialNumber: "",
        Trading_Explain: "",
        Trading_Detail_SerialNumber: "",
        Trading_Percentage: "",
        Trading_Days: "",
        Min_Quantity: "",
      })
    },
    Rdcwholesalepaystages() {
      if (this.form.Children.wholesale_unitprice_paystages.length > 1) {
        this.form.Children.wholesale_unitprice_paystages.pop()
      }
    },
    Unit_Price(e,obj){
      obj.User_Identity.forEach(item=>{
        item.Full_Payment.Unit_Price = e
        item.Payment_Days.forEach(i=>{
          i.Unit_Price = e
        })
      })
    },
    Min_Quantity(e,obj){
      obj.User_Identity.forEach(item=>{
        item.Full_Payment.Min_Quantity = e
        item.Payment_Days.forEach(i=>{
          i.Min_Quantity = e
        })
      })
    },
    User_Type(e,User){
      User.Full_Payment.User_Type = e
      User.Payment_Days.forEach(i=>{
        i.User_Type = e
      })
    },
    addPaystages() {//新增方案
      this.PayWay.push({
        Min_Quantity: 0,
        Unit_Price:'',
        checkboxGroup:['0','1'],
        User_Identity:[{
          User_Type:'0',
          Full_Payment: {
            Wholesale_Unit_Price_Paystages_SerialNumber:'',
            Wholesale_Unit_Price_SerialNumber:'',
            Trading_Explain:"全款",
            Trading_Detail_SerialNumber:'T01000000000001',
            Trading_Percentage:95,
            Trading_Days:0,
            Unit_Price:0,
            User_Type:'0',
            Transaction_Type:0,
            Min_Quantity:0,
          },
          Payment_Days: [{
            Wholesale_Unit_Price_Paystages_SerialNumber:'',
            Wholesale_Unit_Price_SerialNumber:'',
            Trading_Explain:'',
            Trading_Detail_SerialNumber:'',
            Trading_Percentage:0,
            Trading_Days:0,
            Unit_Price:0,
            User_Type:'0',
            Transaction_Type:1,
            Min_Quantity:0,
            PaymentDetail:this.Pay,
            Sort:''
          },{
            Wholesale_Unit_Price_Paystages_SerialNumber:'',
            Wholesale_Unit_Price_SerialNumber:'',
            Trading_Explain:'',
            Trading_Detail_SerialNumber:'',
            Trading_Percentage:0,
            Trading_Days:0,
            Unit_Price:0,
            User_Type:'0',
            Transaction_Type:1,
            Min_Quantity:0,
            PaymentDetail:this.Pay,
            Sort:''
          }],
          isArr:[]
        }]
      })
      // this.ChangeNum(this.form.Starting_Quantity)
    },
    removePaystages() {//删除方案
      if (this.PayWay.length > 1) {
        this.PayWay.pop()
      } else {
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },
    addUserIdentity(obj){
      if(obj.User_Identity.length < this.UserType.length){
        obj.User_Identity.push({
          User_Type:'0',
          Full_Payment: {
            Wholesale_Unit_Price_Paystages_SerialNumber:'',
            Wholesale_Unit_Price_SerialNumber:'',
            Trading_Explain:"全款",
            Trading_Detail_SerialNumber:'T01000000000001',
            Trading_Percentage:95,
            Trading_Days:0,
            Unit_Price:obj.Unit_Price,
            Transaction_Type:0,
            Min_Quantity:obj.Min_Quantity,
          },
          Payment_Days: [{
            Wholesale_Unit_Price_Paystages_SerialNumber:'',
            Wholesale_Unit_Price_SerialNumber:'',
            Trading_Explain:'',
            Trading_Detail_SerialNumber:'',
            Trading_Percentage:0,
            Trading_Days:0,
            Unit_Price:obj.Unit_Price,
            User_Type:'0',
            Transaction_Type:1,
            Min_Quantity:obj.Min_Quantity,
            PaymentDetail:this.Pay,
            Sort:''
          },{
            Wholesale_Unit_Price_Paystages_SerialNumber:'',
            Wholesale_Unit_Price_SerialNumber:'',
            Trading_Explain:'',
            Trading_Detail_SerialNumber:'',
            Trading_Percentage:0,
            Trading_Days:0,
            Unit_Price:obj.Unit_Price,
            User_Type:'0',
            Transaction_Type:1,
            Min_Quantity:obj.Min_Quantity,
            PaymentDetail:this.Pay,
            Sort:''
          }],
          isArr:[]
        })
      }else{
        this.$message({
          message: '没有更多用户类型，不能在增加了',
          type: 'warning'
        })
      }
    },
    removeUserIdentity(obj){
      if (obj.User_Identity.length > 1) {
        obj.User_Identity.pop()
      }else{
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },
    addPayWay(User,obj) {
      if (User.Payment_Days.length < this.Pay.length) {
        User.Payment_Days.push({
          Wholesale_Unit_Price_Paystages_SerialNumber:'',
          Wholesale_Unit_Price_SerialNumber:'',
          Trading_Explain:'',
          Trading_Detail_SerialNumber:'',
          Trading_Percentage:0,
          Trading_Days:0,
          Unit_Price:obj.Unit_Price,
          User_Type:'0',
          Transaction_Type:1,
          Min_Quantity:obj.Min_Quantity,
          PaymentDetail:this.Pay,
          Sort:''
        })
      } else {
        this.$message({
          message: '不能在增加了',
          type: 'warning'
        })
      }
    },
    removePayWay(User) {
      if (User.Payment_Days.length > 2) {
        let i = User.Payment_Days.length - 1
        User.isArr = User.isArr.filter(item => item.index != i)
        User.Payment_Days.pop()
      } else {
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },
    ChangePaymentDetail(e, i, item,User) {
      if (item.Trading_Detail_SerialNumber == "") {//删除
        User.isArr= User.isArr.filter(item => item.index != i)
      } else if (User.isArr.some(item => item.index == i)) {//替换
        User.isArr.forEach(item => {
          if (item.index == i) {
            item.id = e
          }
        })
      } else {//首次添加
        User.isArr.push({
          id: e,
          index: i
        })
      }
      item.Trading_Explain = item.PaymentDetail[i].Trading_Detail_Name
      item.Sort = item.PaymentDetail[i].Sort
    },
    MinQuantity(e, id) {
      this.PayWay[id].forEach(item => {
        item.Min_Quantity = e
      })
    },
    ChangeArticle(Article_SerialNumber) {
      let _this = this;
      this.form.Article_Specifications_SerialNumber = ''
      $.ajax({
        url: DomainName + '/getInquiryIDAction?token=' + $.cookie("token"),
        type: 'POST',
        data: {
          Data:'article_specifications',
          Primary_Key:Article_SerialNumber,
          Primary_Key_Name:'Article_SerialNumber',
          isNullEnterprise:true
        },
        success: function (res) {
          console.log(res)
          _this.article_specifications = res
        }
      })
      if (this.form.Independence=='0') {
        this.getWares(() => {
          if (Article_SerialNumber != '') {
            $.ajax({
              url: DomainName + '/getWarehouseGoodsID?token=' + $.cookie("token"),
              type: 'POST',
              data: {
                Article_SerialNumber,
              },
              success: function (res) {
                console.log(res)
                if (res.Data.length > 0) {
                  _this.disabledSelect = false
                  _this.Wares = res.Data
                  _this.form.Children.wholesale_unitprice_warehouse[0].Wares = res.Data
                }
              }
            })
          } else {
            _this.disabledSelect = true
          }
        })
      }
    },
    getWares(callback) {//获取可选择的所有仓库
      this.form.Children.wholesale_unitprice_warehouse = [{
        Wholesale_Unit_Price_Warehouse_SerialNumber: "",
        Wholesale_Unit_Price_SerialNumber: "",
        Warehouse_SerialNumber: "",//仓库流水号
        Warehouse_Sort: 1,//优先级
        Wares: []
      }]
      this.isWares = []
      if (callback) {
        callback()
      }
    },
    ChangeSort(e) {
      let Sort = []
      this.form.Children.wholesale_unitprice_warehouse.forEach(item => {
        Sort.push(item.Warehouse_Sort)
      })
      let choose = false
      for (let i = 0; i++; i < Sort.length) {
        for (let j = 0; j++; j < Sort.length) {
          if (Sort[i] == Sort[j]) {
            choose = true
          }
        }
      }
      if (choose) {
        this.$message({
          message: '优先级不能有相同',
          type: 'error'
        })
        this.form.Children.wholesale_unitprice_warehouse.forEach(item => {
          item.Warehouse_Sort = this.form.Children.wholesale_unitprice_warehouse.length
        })
      }
    },
    ChangeWare(e, i) {
      if (!this.isWares.some(item => item.index == i)) {
        this.isWares.push({ index: i, value: e })
      } else {
        this.isWares.forEach(item => {
          if (item.index == i) {
            item.value = e
          }
        })
      }
    },
    add_wholesale_unitprice_detail() {//添加多级价格
      this.form.Children.wholesale_unitprice_detail.push({     //采购价格单
        Wholesale_Unit_Price_Detail_SerialNumber: '',
        Wholesale_Unit_Price_SerialNumber: '',  //外键
        Quantity_Interval: '',    //数量区间
        Unit_Price: '',   //价格
        StartNum: '',
        EndNum: ''
      })
    },
    remove_wholesale_unitprice_detail() {//减少多级价格
      if (this.form.Children.wholesale_unitprice_detail.length > 1) {
        let i = this.form.Children.wholesale_unitprice_warehouse.length - 1
        this.isWares = this.isWares.filter(item => item.index != i)
        this.form.Children.wholesale_unitprice_detail.pop()
      } else {
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },
    add_wholesale_unitprice_warehouse() {//添加选择的仓库
      if (this.Wares.length == this.form.Children.wholesale_unitprice_warehouse.length) {
        this.$message({
          message: '不能在添加了',
          type: 'warning'
        })
        return
      }
      this.form.Children.wholesale_unitprice_warehouse.push({
        Wholesale_Unit_Price_Warehouse_SerialNumber: "",
        Wholesale_Unit_Price_SerialNumber: "",
        Warehouse_SerialNumber: "",//仓库流水号
        Warehouse_Sort: this.form.Children.wholesale_unitprice_warehouse.length + 1,//优先级
        Wares: this.Wares
      })
      this.disabled = false
    },
    remove_wholesale_unitprice_warehouse() {//减少选择的仓库
      if (this.form.Children.wholesale_unitprice_warehouse.length > 1) {
        let i = this.form.Children.wholesale_unitprice_warehouse.length - 1
        this.isWares = this.isWares.filter(item => item.index != i)
        this.form.Children.wholesale_unitprice_warehouse.pop()
      } else {
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    getUserType(){//获取所有可选商户类型
      let this_ = this;
      $.ajax({
        url: DomainName + '/getInquiryAction?token='+$.cookie("token"),
        type: 'POST',
        data: {
          Data:'merchant_info',
        },
        success: function (res) {
          console.log(res)
          res.forEach(item=>{
            this_.UserType.push({
              id:item.Merchant_SerialNumber,
              value:item.Merchant_Type
            })
          })
        }
      })
    },
  }
})